package com.app.twth.ui.adjust.redamage.newsku;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.base.BaseCameraPhotoActivity;
import com.app.twth.databinding.ActivityRedamageNewSkuBinding;
import com.app.twth.databinding.DialogRedamageDetailBinding;
import com.app.twth.ui.adjust.redamage.ReDamage;
import com.app.twth.ui.adjust.redamage.ReDamageAdapter;
import com.app.twth.ui.adjust.redamage.ReDamageQr;
import com.app.twth.ui.adjust.redamage.oldsku.RDOldSkuActivity;
import com.app.twth.ui.adjust.redamage.oldsku.RDOldSkuViewModel;
import com.app.twth.ui.b2cpick.submit.SKUBarcodes;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;
import com.app.twth.widget.MoneyTextWatcher;

public class RDNewSkuActivity extends BaseCameraPhotoActivity<ActivityRedamageNewSkuBinding, RDOldSkuViewModel> {
    private String TAG = getClass().getSimpleName();

    private int type = 0;
    private int index = 0;
    private ReDamage reDamage;
    private String length_path, width_path, height_path, weight_path;

    @Override
    protected String setTitle() {
        return "Damage(New SKU)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext("");
        setRight("Scan");
        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        reDamage = (ReDamage) bundle.getSerializable("data");

        binding.tvContaier.setText(reDamage.getContainerNo());
        binding.tvIblpn.setText(reDamage.getLpn());
        binding.tvSkuQuantity.setText(reDamage.getSku() + "(" + reDamage.getQty() + ")");
        binding.tvNewSku.setText(reDamage.getNewSku());

        binding.tvCodeLpn.requestFocus();

        binding.tvCode.setOnEditorActionListener(EnterListenter);

        binding.tvCode.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvCodeLpn.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvQty.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvLength.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvWidth.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvHeight.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvWeight.setOnFocusChangeListener(onFocusChangeListener);

        binding.tvLength.addTextChangedListener(new MoneyTextWatcher(binding.tvLength));
        binding.tvWidth.addTextChangedListener(new MoneyTextWatcher(binding.tvWidth));
        binding.tvHeight.addTextChangedListener(new MoneyTextWatcher(binding.tvHeight));
        binding.tvWeight.addTextChangedListener(new MoneyTextWatcher(binding.tvWeight));

        binding.tvCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                viewModel.skuBarcodesLiveData.setValue(null);
                binding.tvQty.setText("");
            }
        });

        if ((reDamage.getProcessList() == null) || (reDamage.getProcessList().size() == 0)) {
            binding.ivSkuQuantity.setVisibility(View.GONE);
        }

    }

    @Override
    protected void initListener() {
        viewModel.skuBarcodesLiveData.observe(this, data -> {
            boolean isSKU = false;
            if (data.getSku().equalsIgnoreCase(reDamage.getNewSku())) {
                isSKU = true;
            }
            if (data.getBarcodeList() != null) {
                for (String str : data.getBarcodeList()) {
                    if (str.equalsIgnoreCase(reDamage.getNewSku())) {
                        isSKU = true;
                    }
                }
            }
            if (isSKU) {
                binding.tvQty.requestFocus();
                binding.tvQty.setText("1");
            } else {
                viewModel.skuBarcodesLiveData.setValue(null);
                binding.tvQty.setText("");
            }

        });

        viewModel.fileUploadMutableLiveData.observe(this, data -> {
            Log.e(TAG, "type():" + data.getType() + ",position:" + data.getPosition());
            switch (data.getType()) {
                case 0:
                    length_path = data.getPath();
                    break;
                case 1:
                    width_path = data.getPath();
                    break;
                case 2:
                    height_path = data.getPath();
                    break;
                case 3:
                    weight_path = data.getPath();
                    break;
            }
            if (data.isSubmit()) {
                setSubmit();
            }
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_sku:
                if (reDamage.getProcessList() == null) {
                    return;
                }
                if (reDamage.getProcessList().size() == 0) {
                    return;
                }
                showReDamageDetailDialog();
                break;
            case R.id.iv_scan_lpn:
                type = 0;
                setScan();
                break;
            case R.id.iv_scan:
                type = 1;
                setScan();
                break;
            case R.id.tv_right:
                setScan();
                break;
            case R.id.iv_qty:
                String cartonsQty = binding.tvQty.getText().toString();
                if (Utils.isEmpty(cartonsQty)) {
                } else if (Integer.parseInt(cartonsQty) > 1) {
                    binding.tvQty.setText((Integer.parseInt(cartonsQty) - 1) + "");
                } else {
                    binding.tvQty.setText("0");
                }
                break;
            case R.id.iv_length:
                index = 0;
                setCameraPhotoOrShow(binding.ivLengthDelete, length_path, "length");
                break;
            case R.id.iv_length_delete:
                length_path = "";
                deleteImg(binding.ivLength, binding.ivLengthDelete);

                break;
            case R.id.iv_width:
                index = 1;
                setCameraPhotoOrShow(binding.ivWidthDelete, width_path, "width");
                break;
            case R.id.iv_width_delete:
                width_path = "";
                deleteImg(binding.ivWidth, binding.ivWidthDelete);
                break;
            case R.id.iv_height:
                index = 2;
                setCameraPhotoOrShow(binding.ivHeightDelete, height_path, "height");
                break;
            case R.id.iv_height_delete:
                height_path = "";
                deleteImg(binding.ivHeight, binding.ivHeightDelete);
                break;
            case R.id.iv_weight:
                index = 3;
                setCameraPhotoOrShow(binding.ivWeightDelete, weight_path, "weight");
                break;
            case R.id.iv_weight_delete:
                weight_path = "";
                deleteImg(binding.ivWeight, binding.ivWeightDelete);
                break;
            case R.id.tv_reset:
                reset(1);
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < 1000) {
                    return;
                }
                timeMillis = System.currentTimeMillis();
                String sku_barcode = binding.tvCode.getText().toString();
                if (Utils.isEmpty(sku_barcode)) {
                    ToastUtil.showToast("Please enter the SKU/Barcode");
                    return;
                }

                setSubmit();
                break;
        }
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCode.getText().toString();
                reset(1);
                binding.tvCode.setText(barcodeStr);
                viewModel.getInfoByBarcode(barcodeStr);
                binding.tvQty.setText("");
            }
            return false;
        }
    };

    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                type = 0;
                return;
            }

            switch (v.getId()) {
                case R.id.tv_code_lpn:
                    type = 0;
                    break;
                case R.id.tv_code:
                    type = 1;
                    break;
                case R.id.tv_qty:
                    type = 2;
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ForResult2 && resultCode == RESULT_OK) {
            Log.e(TAG, "onActivityResult");
            finish();
        }
    }

    @Override
    protected void getImgPath(String path) {
        setPath(index, path);
    }

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        bottomLayoutBinding.tvHint.setText("");
        switch (type) {
            case 0:
                binding.tvCodeLpn.setText(barcodeStr);
                break;
            case 1:
                viewModel.getInfoByBarcode(barcodeStr);
                binding.tvCode.setText(barcodeStr);
                binding.tvQty.setText("");
                break;
            case 2:
                try {
                    String barCode = binding.tvCode.getText().toString();
                    if (Utils.isEmpty(barCode)) {
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                        return;
                    }
                    Log.e(TAG, "barCode:" + barCode);
                    Log.e(TAG, "barcodeStr:" + barcodeStr);
                    SKUBarcodes skuBarcodes = viewModel.skuBarcodesLiveData.getValue();
                    if (skuBarcodes == null) {
                        ToastUtil.showToast(getString(R.string.scan_inbound_lpn_lower));
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                        return;
                    }

                    if ((skuBarcodes.getBarcodeList() != null) && (skuBarcodes.getBarcodeList().size() > 0)) {
                        for (String barcode : skuBarcodes.getBarcodeList()) {
                            if (barCode.equalsIgnoreCase(barcode)) {
                                String qty = binding.tvQty.getText().toString();
                                if (Utils.isEmpty(qty)) {
                                    binding.tvQty.setText(1 + "");
                                    return;
                                } else {
                                    binding.tvQty.setText((1 + Integer.parseInt(qty)) + "");
                                    return;
                                }
                            }
                        }
                    } else if (barCode.equalsIgnoreCase(barcodeStr)) {
                        String qty = binding.tvQty.getText().toString();
                        if (Utils.isEmpty(qty)) {
                            binding.tvQty.setText(1 + "");
                        } else {
                            binding.tvQty.setText((1 + Integer.parseInt(qty)) + "");
                        }
                    } else {
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void setRemove(int type) {
        switch (type) {
            case 0:
                length_path = "";
                deleteImg(binding.ivLength, binding.ivLengthDelete);
                break;
            case 1:
                width_path = "";
                deleteImg(binding.ivWidth, binding.ivWidthDelete);
                break;
            case 2:
                height_path = "";
                deleteImg(binding.ivHeight, binding.ivHeightDelete);
                break;
            case 3:
                weight_path = "";
                deleteImg(binding.ivWeight, binding.ivWeightDelete);
                break;
        }
    }

    private void reset(int level) {
        binding.tvCodeLpn.requestFocus();
        binding.tvCodeLpn.setText("");
        binding.tvCode.setText("");
        binding.tvQty.setText("");
        binding.tvLength.setText("");
        binding.tvWidth.setText("");
        binding.tvHeight.setText("");
        binding.tvWeight.setText("");

        viewModel.skuBarcodesLiveData.setValue(null);

        length_path = "";
        deleteImg(binding.ivLength, binding.ivLengthDelete);
        width_path = "";
        deleteImg(binding.ivWidth, binding.ivWidthDelete);
        height_path = "";
        deleteImg(binding.ivHeight, binding.ivHeightDelete);
        weight_path = "";
        deleteImg(binding.ivWeight, binding.ivWeightDelete);

        if (1 < level) {
            binding.tvCode.requestFocus();
        }
        binding.tvLength.setTextColor(getResources().getColor(R.color.black));
        binding.tvWidth.setTextColor(getResources().getColor(R.color.black));
        binding.tvHeight.setTextColor(getResources().getColor(R.color.black));
        binding.tvWeight.setTextColor(getResources().getColor(R.color.black));
    }

    private void setSubmit() {
        Log.e(TAG, "setSubmit");

        String lpn = binding.tvCodeLpn.getText().toString();
        if (Utils.isEmpty(lpn)) {
            ToastUtil.showToast("Please enter the lpn");
            return;
        }
        if (!lpn.equalsIgnoreCase(reDamage.getLpn())) {
            ToastUtil.showToast("Invalid IBLPN,please rescan");
            return;
        }

        String sku_barcode = binding.tvCode.getText().toString();
        if (Utils.isEmpty(sku_barcode)) {
            ToastUtil.showToast("Please enter the new SKU/Barcode");
            return;
        }
        String qtyStr = binding.tvQty.getText().toString();
        if (Utils.isEmpty(qtyStr)) {
            qtyStr = "0";
        }
        int qty = Integer.parseInt(qtyStr);
        if (qty < 1) {
            ToastUtil.showToast("errro：exceed QTY");
            return;
        }
        if (qty != reDamage.getQty()) {//数量不等
            ToastUtil.showToast("errro：exceed QTY");
            return;
        }

        String length = binding.tvLength.getText().toString();
        if (!judgeType(length, "Please enter the length")) {
            return;
        }
        String width = binding.tvWidth.getText().toString();
        if (!judgeType(width, "Please enter the width")) {
            return;
        }
        String height = binding.tvHeight.getText().toString();
        if (!judgeType(height, "Please enter the height")) {
            return;
        }
        String weight = binding.tvWeight.getText().toString();
        if (!judgeType(weight, "Please enter the weight")) {
            return;
        }

        if (Utils.isEmpty(length_path)) {
            ToastUtil.showToast("Please add length photo");
            return;
        }
        if (Utils.isEmpty(width_path)) {
            ToastUtil.showToast("Please add width photo");
            return;
        }
        if (Utils.isEmpty(height_path)) {
            ToastUtil.showToast("Please add height photo");
            return;
        }
        if (Utils.isEmpty(weight_path)) {
            ToastUtil.showToast("Please add weight photo");
            return;
        }

        if (!Utils.isEmpty(length_path)) {
            if (!length_path.contains("http")) {
                viewModel.fileUpload(reDamage.getContainerNo(), "length", length_path, 0, true, true);
                return;
            }
        }
        if (!Utils.isEmpty(width_path)) {
            if (!width_path.contains("http")) {
                viewModel.fileUpload(reDamage.getContainerNo(), "width", width_path, 1, true, true);
                return;
            }
        }
        if (!Utils.isEmpty(height_path)) {
            if (!height_path.contains("http")) {
                viewModel.fileUpload(reDamage.getContainerNo(), "height", height_path, 2, true, true);
                return;
            }
        }
        if (!Utils.isEmpty(weight_path)) {
            if (!weight_path.contains("http")) {
                viewModel.fileUpload(reDamage.getContainerNo(), "weight", weight_path, 3, true, true);
                return;
            }
        }

        ReDamageQr reDamageQr = new ReDamageQr();
        reDamageQr.setWeight(Double.parseDouble(weight));
        reDamageQr.setLength(Double.parseDouble(length));
        reDamageQr.setWidth(Double.parseDouble(width));
        reDamageQr.setHeight(Double.parseDouble(height));

        reDamageQr.setWeightPhoto(weight_path);
        reDamageQr.setLengthPhoto(length_path);
        reDamageQr.setWidthPhoto(width_path);
        reDamageQr.setHeightPhoto(height_path);

        Bundle bundle1 = new Bundle();
        bundle1.putSerializable("data", reDamage);
        bundle1.putSerializable("ReDamageQr", reDamageQr);
        AppRouter.showActivityForResult(mContext, RDOldSkuActivity.class, bundle1, Constant.ForResult2);
    }

    private boolean judgeType(String mold, String hint) {
        if (Utils.isEmpty(mold)) {
            ToastUtil.showToast(hint);
            return false;
        }

        if (Double.parseDouble(mold) <= 0) {
            ToastUtil.showToast(hint);
            return false;
        }
        return true;
    }

    //=================================================
    private void setCameraPhotoOrShow(ImageView iv_delete, String path, String name) {
        temp_path = path;
        if (iv_delete.getVisibility() == View.VISIBLE) {
            showPhotoDialog(temp_path);
        } else {
            requestCamera(name);
        }
    }

    private void setPath(int type, String pathImage) {
        Log.e(TAG, "setPath>type:" + type + ",pathImage:" + pathImage);
        if (!pathImage.contains("http")) {//选择的图片
            String fileName = "";
            switch (type) {
                case 0:
                    fileName = "length";
                    break;
                case 1:
                    fileName = "width";
                    break;
                case 2:
                    fileName = "height";
                    break;
                case 3:
                    fileName = "weight";
                    break;
            }
            viewModel.fileUpload(reDamage.getContainerNo(), fileName, pathImage, type, false, false);
        }
        switch (type) {
            case 0:
                length_path = pathImage;
                setShow(length_path, binding.ivLength, binding.ivLengthDelete);
                break;
            case 1:
                width_path = pathImage;
                setShow(width_path, binding.ivWidth, binding.ivWidthDelete);
                break;
            case 2:
                height_path = pathImage;
                setShow(height_path, binding.ivHeight, binding.ivHeightDelete);
                break;
            case 3:
                weight_path = pathImage;
                setShow(weight_path, binding.ivWeight, binding.ivWeightDelete);
                break;
        }
    }

    private AlertDialog dialogReDamageDetail;

    private void showReDamageDetailDialog() {
        dialogReDamageDetail = MyDialogUtil.getDialog(mContext, initReDamageDetailDialogView(), Gravity.CENTER);
        dialogReDamageDetail.setCanceledOnTouchOutside(true);
        dialogReDamageDetail.show();
    }

    ReDamageAdapter tallyDetailAdapter;

    private View initReDamageDetailDialogView() {
        DialogRedamageDetailBinding dialogBinding = DialogRedamageDetailBinding.inflate(getLayoutInflater());

        tallyDetailAdapter = new ReDamageAdapter(this, reDamage.getProcessList());

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        dialogBinding.recyclerviewDetail.setLayoutManager(layoutManager1);
        dialogBinding.recyclerviewDetail.setAdapter(tallyDetailAdapter);

        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogReDamageDetail != null) {
                dialogReDamageDetail.dismiss();
            }
        });
        return dialogBinding.getRoot();
    }

}
